<?php
/**
 * Description of LeilaoDAO
 *
 * @author Magno
 */
class LeilaoDAO {

    private $conexao;

    private $cronometroDAO;
    private $mediaDAO;
    private $tipoLeilaoDAO;
    private $statusDAO;
    private $adminDAO;
    private $produtoDAO;
    private $lancesDAO;

    public function __construct() {
        $this->conexao = Conexao::getConexao();

        $this->cronometroDAO = new CronometroDAO();
        $this->mediaDAO = new MediaDAO();
        $this->tipoLeilaoDAO = new TipoLeilaoDAO();
        $this->adminDAO = new AdminDAO();
        $this->statusDAO = new StatusDAO();
        $this->produtoDAO = new ProdutoDAO();
        $this->lancesDAO = new LanceDAO();

    }

    public function salvar($leilao) {

        try {

            if ($leilao->getLeilaoID() != null && $leilao->getLeilaoID() > 0) {

                $statment = $this->conexao->prepare("UPDATE leilao SET
                        inicio = :inicio,
                        mediaID = :mediaID,
                        usuarioID = :usuarioID,
                        tipoLeilaoID = :tipoLeilaoID,
                        cronometroID = :cronometroID,
                        statusID = :statusID
                        WHERE leilaoID = :leilaoID");
            } else {

                $statment = $this->conexao->prepare("INSERT INTO leilao(leilaoID,inicio,mediaID,usuarioID,tipoLeilaoID,cronometroID,statusID)
                    VALUES (:leilaoID,:inicio,:mediaID,:usuarioID,:tipoLeilaoID,:cronometroID,:statusID);");
            }

            if ($statment->execute($leilao->toBD())) {

                if ($leilao->getLeilaoID() == null || $leilao->getLeilaoID() <= 0)
                    $leilao->setLeilaoID($this->conexao->lastInsertId());
                return $leilao;
            }else {
                $erros = $statment->errorInfo();
                throw new Exception("Erro LeilaoDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro LeilaoDAO:" . $err->getMessage());
        }
    }

    public function excluir($leilaoID) {

        try {

            $statment = $this->conexao->prepare("DELETE FROM leilao WHERE leilaoID = :leilaoID");
            $statment->bindParam(':leilaoID', $leilaoID);

            if (!$statment->execute()) {
                $erros = $statment->errorInfo();
                throw new Exception("Erro LeilaoDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro LeilaoDAO:" . $err->getMessage());
        }
    }

    public function listar($pagina = 0, $inicio = "", $tipoLeilaoID = -1, $cronometroID = -1, $statusID = -1, $usuarioID = -1, $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina);
            $where = $this->getWhere($inicio, $tipoLeilaoID, $cronometroID, $statusID, $usuarioID);
            $leilaos = array();
            $statment = $this->conexao->query("SELECT * FROM leilao u $where $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $leilao = new LeilaoBean($row['leilaoID'], $row['inicio']);
                $leilao->setStatus($this->statusDAO->buscarPorID($row['statusID']));

                if($carregarDependencias){
                    $leilao->setCronometro($this->cronometroDAO->buscarPorID($row['cronometroID']));
                    $leilao->setTipoLeilao($this->tipoLeilaoDAO->buscarPorID($row['tipoLeilaoID']));
                    $leilao->setMedia($this->mediaDAO->buscarPorID($row['mediaID']));
                    $leilao->setAdmin($this->adminDAO->buscarPorID($row['adminDAO']));
                    $leilao->setProdutos($this->produtoDAO->listar(0, "", 0, $row['leilaoID'], 0, false));
                    $leilao->setLances($this->lancesDAO->listar(0, $row['leilaoID'], 0, false));
                }

                $leilaos[] =  $leilao;
            }

            return $leilaos;
        } catch (PDOException $err) {
            throw new Exception("Erro LeilaoDAO:" . $err->getMessage());
        }
    }

    public function listarPorOrdem($pagina = 0, $tamanho = 0, $ordem = "leilaoID", $direcao = "ASC", $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina,$tamanho);
            $leilaos = array();
            $statment = $this->conexao->query("SELECT * FROM leilao u ORDER BY u.$ordem $direcao $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $leilao = new LeilaoBean($row['leilaoID'], $row['inicio']);
                $leilao->setStatus($this->statusDAO->buscarPorID($row['statusID']));

                if($carregarDependencias){
                    $leilao->setCronometro($this->cronometroDAO->buscarPorID($row['cronometroID']));
                    $leilao->setTipoLeilao($this->tipoLeilaoDAO->buscarPorID($row['tipoLeilaoID']));
                    $leilao->setMedia($this->mediaDAO->buscarPorID($row['mediaID']));
                    $leilao->setAdmin($this->adminDAO->buscarPorID($row['adminDAO']));
                    $leilao->setProdutos($this->produtoDAO->listar(0, "", 0, $row['leilaoID'], 0, false));
                    $leilao->setLances($this->lancesDAO->listar(0, $row['leilaoID'], 0, false));
                }

                $leilaos[] = $leilao;
            }

            return $leilaos;
        } catch (PDOException $err) {
            throw new Exception("Erro LeilaoDAO:" . $err->getMessage());
        }
    }

    public function buscarPorID($leilaoID, $carregarDependencias = false) {
        try {

            $row = $this->conexao->query("SELECT * FROM leilao WHERE leilaoID = $leilaoID ")->fetch(PDO::FETCH_SERIALIZE);

            if (isset ($row['leilaoID']) && $row['leilaoID'] > 0) {
                $leilao = new LeilaoBean($row['leilaoID'], $row['inicio']);
                $leilao->setStatus($this->statusDAO->buscarPorID($row['statusID']));

                if($carregarDependencias){
                    $leilao->setCronometro($this->cronometroDAO->buscarPorID($row['cronometroID']));
                    $leilao->setTipoLeilao($this->tipoLeilaoDAO->buscarPorID($row['tipoLeilaoID']));
                    $leilao->setMedia($this->mediaDAO->buscarPorID($row['mediaID']));
                    $leilao->setAdmin($this->adminDAO->buscarPorID($row['adminDAO']));
                    $leilao->setProdutos($this->produtoDAO->listar(0, "", 0, $row['leilaoID'], 0, false));
                    $leilao->setLances($this->lancesDAO->listar(0, $row['leilaoID'], 0, false));
                }

                return $leilao;
            } else {
                return null;
            }
        } catch (PDOException $err) {
            throw new Exception("Erro LeilaoDAO:" . $err->getMessage());
        }
    }

    protected function getWhere($inicio = "", $tipoLeilaoID = -1, $cronometroID = -1, $statusID = -1, $usuarioID = -1) {

        $where = " WHERE 1 = 1 ";

        if (isset($inicio) && strlen($inicio) > 0) {
            $where = $where . " AND u.inicio = '$inicio' ";
        }

        if (isset($tipoLeilaoID) && $tipoLeilaoID > 0) {
            $where = $where . " AND u.tipoLeilaoID = $tipoLeilaoID ";
        }

        if (isset($cronometroID) && $cronometroID > 0) {
            $where = $where . " AND u.cronometroID = $cronometroID ";
        }

        if (isset($statusID) && $statusID > 0) {
            $where = $where . " AND u.statusID = $statusID ";
        }

        if (isset($usuarioID) && $usuarioID > 0) {
            $where = $where . " AND u.tipoLeilaoID = $tipoLeilaoID ";
        }

        return $where;
    }

    public function total($inicio = "", $tipoLeilaoID = -1, $cronometroID = -1, $statusID = -1, $usuarioID = -1) {
        try {
            $where = $this->getWhere($inicio, $tipoLeilaoID, $cronometroID, $statusID, $usuarioID);
            $total = $this->conexao->query("SELECT COUNT(u.leilaoID) total FROM leilao u $where")->fetch(PDO::FETCH_COLUMN);
            return $total;
        } catch (PDOException $err) {
            throw new Exception("Erro LeilaoDAO:" . $err->getMessage());
        }
    }

}
?>
